package com.ext.aic.box.wx;

import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.ext.aic.beans.box.ChatWindowElement;
import com.ext.aic.beans.box.ConversationWindowElement;
import com.ext.aic.box.TripartiteLoginStatus;
import com.ext.aic.box.logs.WxReplyRequestLogsManager;
import com.ext.aic.box.wx.chat.ChatManager;
import com.ext.aic.box.wx.conversation.ConversationManager;
import com.ext.aic.events.OnAccessibilityListener;
import com.ext.aic.events.OnAccessibilityServiceEvent;
import com.ext.aic.handler.NotificationHandler;
import com.ext.aic.utils.BoxUtils;
import com.ext.aic.utils.WxElementUtils;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;

import java.util.List;
import java.util.Objects;

import lombok.Getter;

@Getter
public class WxAccessibilityInterceptor implements OnAccessibilityListener {

    private WxViews wxViews = new WxViews();
    @Getter
    private ConversationManager conversationManager = new ConversationManager();
    private NotificationHandler notificationHandler = new NotificationHandler();
    private long lastUserActionTime;
    private boolean conversationAnalyzing; //会话是否解析中

    @Override
    public void onWindowContentChangedCall() {
        OnAccessibilityServiceEvent serviceEvent = BoxUtils.getInstance().getServiceEvent();
        TripartiteLoginStatus.getInstance().setLoginPcWeChat(checkWeChatLoginPrompt(false));
        AccessibilityNodeInfo rootNode = serviceEvent.getRootNode();
        if (wxViews.hasConversationWindow(rootNode)) {
            WxReplyRequestLogsManager.getInstance().exitDetection();
            if ((conversationManager.isProcessNotifyAnalyze() ||
                    (!conversationManager.isDetecting() && !conversationManager.isRolling()))) {
                conversationAnalyzing = true;
                ConversationWindowElement conversation = wxViews.findConversationWindowElement(rootNode);
                conversationManager.analyzeConversationList(conversation, rootNode);
            } else {
                conversationAnalyzing = false;
                //当任务挂起时重新触发回复任务
                if (serviceEvent.getReplyTaskCount().get() == 1) {
                    serviceEvent.triggerReplyTask(null);
                }
            }
        } else if (wxViews.hasChatWindow(rootNode)) {
            ChatManager chatManager = serviceEvent.getChatManager();
            if (chatManager.isTobeAssignedWithChat()) {
                ChatWindowElement chat = wxViews.findChatWindowElement(rootNode);
                chatManager.initChat(chat);
            }
        }
    }

    @Override
    public void onWindowStateChangedCall() {
        TripartiteLoginStatus.getInstance().setLoginPcWeChat(checkWeChatLoginPrompt(false));
    }

    @Override
    public void onNotificationStateCall() {

    }

    private boolean checkWeChatLoginPrompt(boolean isNotify) {
        try {
            OnAccessibilityServiceEvent serviceEvent = BoxUtils.getInstance().getServiceEvent();
            List<String> wxLoginMarks = WxElementUtils.getInstance().getWxLoginMarks();
            if (isNotify) {
                AccessibilityEvent accessibilityEvent = serviceEvent.getAccessibilityEvent();
                List<CharSequence> messages = accessibilityEvent.getText();
                if (ObjectJudge.isNullOrEmpty(messages)) {
                    return false;
                }
                for (CharSequence msg : messages) {
                    String message = Objects.toString(msg, "");
                    boolean hasMatch = wxLoginMarks.stream().filter(mark -> mark != null && !mark.isEmpty()).anyMatch(mark -> message.contains(mark));
                    if (hasMatch) {
                        return true;
                    }
                }
            } else {
                AccessibilityNodeInfo rootNode = serviceEvent.getRootNode();
                if (rootNode != null) {
                    for (String mark : wxLoginMarks) {
                        List<AccessibilityNodeInfo> infos = rootNode.findAccessibilityNodeInfosByText(mark);
                        if (!ObjectJudge.isNullOrEmpty(infos)) {
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onViewScrolledCall() {
        OnAccessibilityServiceEvent serviceEvent = BoxUtils.getInstance().getServiceEvent();
        if (conversationManager.isDetecting() && conversationManager.isRolling()) {
            conversationManager.setRolling(false);
            conversationManager.recognitionNextConversation();
        } else if (!conversationManager.isDetecting()) {
            updateUserActionTime();
            conversationManager.setRolling(false);
        }
    }

    @Override
    public void onViewClicked() {
        if (!conversationManager.isDetecting()) {
            updateUserActionTime();
        }
    }

    @Override
    public void onViewLongClicked() {
        if (!conversationManager.isDetecting()) {
            updateUserActionTime();
        }
    }

    private void updateUserActionTime() {
        OnAccessibilityServiceEvent serviceEvent = BoxUtils.getInstance().getServiceEvent();
        AccessibilityEvent accessibilityEvent = serviceEvent.getAccessibilityEvent();
        AccessibilityNodeInfo source = accessibilityEvent.getSource();
        if (source == null) {
            return;
        }
        String className = Objects.toString(source.getClassName(), "");
        boolean isUserAction = className.contains("ListView") || className.contains("Button") || className.contains("TextView") || className.contains("RecyclerView");
        if (isUserAction) {
            lastUserActionTime = System.currentTimeMillis();
        }
    }
}
